{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "dfe37963-1af6-44fc-a841-8e462443f5e6",
   "metadata": {},
   "source": [
    "## Expert Knowledge Worker\n",
    "\n",
    "### A question answering agent that is an expert knowledge worker\n",
    "### To be used by employees of Insurellm, an Insurance Tech company\n",
    "### The agent needs to be accurate and the solution should be low cost.\n",
    "\n",
    "This project will use RAG (Retrieval Augmented Generation) to ensure our question/answering assistant has high accuracy.\n",
    "\n",
    "## TODAY:\n",
    "\n",
    "- Part A: We will divide our documents into CHUNKS\n",
    "- Part B: We will encode our CHUNKS into VECTORS and put in Chroma\n",
    "- Part C: We will visualize our vectors"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0769edb3",
   "metadata": {},
   "source": [
    "### PART A: Divide our documents into chunks"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ba2779af-84ef-4227-9e9e-6eaf0df87e77",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import glob\n",
    "import tiktoken\n",
    "import numpy as np\n",
    "from dotenv import load_dotenv\n",
    "from langchain_openai import OpenAIEmbeddings\n",
    "from langchain_chroma import Chroma\n",
    "from langchain_huggingface import HuggingFaceEmbeddings\n",
    "from langchain_community.document_loaders import DirectoryLoader, TextLoader\n",
    "from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
    "from sklearn.manifold import TSNE\n",
    "import plotly.graph_objects as go"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "802137aa-8a74-45e0-a487-d1974927d7ca",
   "metadata": {},
   "outputs": [],
   "source": [
    "# price is a factor for our company, so we're going to use a low cost model\n",
    "\n",
    "MODEL = \"gpt-4.1-nano\"\n",
    "db_name = \"vector_db\"\n",
    "load_dotenv(override=True)\n",
    "openai_api_key = os.getenv('OPENAI_API_KEY')\n",
    "if openai_api_key:\n",
    "    print(f\"OpenAI API Key exists and begins {openai_api_key[:8]}\")\n",
    "else:\n",
    "    print(\"OpenAI API Key not set\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "58c85082-e417-4708-9efe-81a5d55d1424",
   "metadata": {},
   "outputs": [],
   "source": [
    "# How many characters in all the documents?\n",
    "\n",
    "knowledge_base_path = \"knowledge-base/**/*.md\"\n",
    "files = glob.glob(knowledge_base_path, recursive=True)\n",
    "print(f\"Found {len(files)} files in the knowledge base\")\n",
    "\n",
    "entire_knowledge_base = \"\"\n",
    "\n",
    "for file_path in files:\n",
    "    with open(file_path, 'r', encoding='utf-8') as f:\n",
    "        entire_knowledge_base += f.read()\n",
    "        entire_knowledge_base += \"\\n\\n\"\n",
    "\n",
    "print(f\"Total characters in knowledge base: {len(entire_knowledge_base):,}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0b53a099",
   "metadata": {},
   "outputs": [],
   "source": [
    "# How many tokens in all the documents?\n",
    "\n",
    "encoding = tiktoken.encoding_for_model(MODEL)\n",
    "tokens = encoding.encode(entire_knowledge_base)\n",
    "token_count = len(tokens)\n",
    "print(f\"Total tokens for {MODEL}: {token_count:,}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ee78efcb-60fe-449e-a944-40bab26261af",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load in everything in the knowledgebase using LangChain's loaders\n",
    "\n",
    "folders = glob.glob(\"knowledge-base/*\")\n",
    "\n",
    "documents = []\n",
    "for folder in folders:\n",
    "    doc_type = os.path.basename(folder)\n",
    "    loader = DirectoryLoader(folder, glob=\"**/*.md\", loader_cls=TextLoader, loader_kwargs={'encoding': 'utf-8'})\n",
    "    folder_docs = loader.load()\n",
    "    for doc in folder_docs:\n",
    "        doc.metadata[\"doc_type\"] = doc_type\n",
    "        documents.append(doc)\n",
    "\n",
    "print(f\"Loaded {len(documents)} documents\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "68dab1ab",
   "metadata": {},
   "outputs": [],
   "source": [
    "documents[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "25987306",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Divide into chunks using the RecursiveCharacterTextSplitter\n",
    "\n",
    "text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)\n",
    "chunks = text_splitter.split_documents(documents)\n",
    "\n",
    "print(f\"Divided into {len(chunks)} chunks\")\n",
    "print(f\"First chunk:\\n\\n{chunks[0]}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9eb209db",
   "metadata": {},
   "outputs": [],
   "source": [
    "chunks[100]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ecee2169",
   "metadata": {},
   "source": [
    "### PART B: Make vectors and store in Chroma\n",
    "\n",
    "In Week 3, you set up a Hugging Face account and got an HF_TOKEN\n",
    "\n",
    "At this point, you might want to add it to your `.env` file and run `load_dotenv(override=True)`\n",
    "\n",
    "(This actually shouldn't be required)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "730711a9-6ffe-4eee-8f48-d6cfb7314905",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Pick an embedding model\n",
    "\n",
    "embeddings = HuggingFaceEmbeddings(model_name=\"all-MiniLM-L6-v2\")\n",
    "#embeddings = OpenAIEmbeddings(model=\"text-embedding-3-large\")\n",
    "\n",
    "if os.path.exists(db_name):\n",
    "    Chroma(persist_directory=db_name, embedding_function=embeddings).delete_collection()\n",
    "\n",
    "vectorstore = Chroma.from_documents(documents=chunks, embedding=embeddings, persist_directory=db_name)\n",
    "print(f\"Vectorstore created with {vectorstore._collection.count()} documents\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "252f17e9-3529-4e81-996c-cfa9f08e75a8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Let's investigate the vectors\n",
    "\n",
    "collection = vectorstore._collection\n",
    "count = collection.count()\n",
    "\n",
    "sample_embedding = collection.get(limit=1, include=[\"embeddings\"])[\"embeddings\"][0]\n",
    "dimensions = len(sample_embedding)\n",
    "print(f\"There are {count:,} vectors with {dimensions:,} dimensions in the vector store\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c30096a7",
   "metadata": {},
   "source": [
    "### Part C: Visualize!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d48dcb6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Prework\n",
    "\n",
    "result = collection.get(include=['embeddings', 'documents', 'metadatas'])\n",
    "vectors = np.array(result['embeddings'])\n",
    "documents = result['documents']\n",
    "metadatas = result['metadatas']\n",
    "doc_types = [metadata['doc_type'] for metadata in metadatas]\n",
    "colors = [['blue', 'green', 'red', 'orange'][['products', 'employees', 'contracts', 'company'].index(t)] for t in doc_types]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7e8decb0-d9b0-4d51-8402-7a6174d22159",
   "metadata": {},
   "outputs": [],
   "source": [
    "# We humans find it easier to visalize things in 2D!\n",
    "# Reduce the dimensionality of the vectors to 2D using t-SNE\n",
    "# (t-distributed stochastic neighbor embedding)\n",
    "\n",
    "tsne = TSNE(n_components=2, random_state=42)\n",
    "reduced_vectors = tsne.fit_transform(vectors)\n",
    "\n",
    "# Create the 2D scatter plot\n",
    "fig = go.Figure(data=[go.Scatter(\n",
    "    x=reduced_vectors[:, 0],\n",
    "    y=reduced_vectors[:, 1],\n",
    "    mode='markers',\n",
    "    marker=dict(size=5, color=colors, opacity=0.8),\n",
    "    text=[f\"Type: {t}<br>Text: {d[:100]}...\" for t, d in zip(doc_types, documents)],\n",
    "    hoverinfo='text'\n",
    ")])\n",
    "\n",
    "fig.update_layout(title='2D Chroma Vector Store Visualization',\n",
    "    scene=dict(xaxis_title='x',yaxis_title='y'),\n",
    "    width=800,\n",
    "    height=600,\n",
    "    margin=dict(r=20, b=10, l=10, t=40)\n",
    ")\n",
    "\n",
    "fig.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7310c9c8-03c1-4efc-a104-5e89aec6db1a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Let's try 3D!\n",
    "\n",
    "tsne = TSNE(n_components=3, random_state=42)\n",
    "reduced_vectors = tsne.fit_transform(vectors)\n",
    "\n",
    "# Create the 3D scatter plot\n",
    "fig = go.Figure(data=[go.Scatter3d(\n",
    "    x=reduced_vectors[:, 0],\n",
    "    y=reduced_vectors[:, 1],\n",
    "    z=reduced_vectors[:, 2],\n",
    "    mode='markers',\n",
    "    marker=dict(size=5, color=colors, opacity=0.8),\n",
    "    text=[f\"Type: {t}<br>Text: {d[:100]}...\" for t, d in zip(doc_types, documents)],\n",
    "    hoverinfo='text'\n",
    ")])\n",
    "\n",
    "fig.update_layout(\n",
    "    title='3D Chroma Vector Store Visualization',\n",
    "    scene=dict(xaxis_title='x', yaxis_title='y', zaxis_title='z'),\n",
    "    width=900,\n",
    "    height=700,\n",
    "    margin=dict(r=10, b=10, l=10, t=40)\n",
    ")\n",
    "\n",
    "fig.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "65489941",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
